/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedModelData, FeatureManager } from '@amcax/base';
import { previewer } from '@app-base/module';
import { docMgr } from '@app-base/module';
import { wsApi } from '@app-base/server';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { previewData } from '@app-cad/common/utils/render';
import { FeatureBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { ctx2 } from '@app-cad/module';
import i18n from 'i18next';
import _ from 'lodash';
import { Group, AxesHelper } from 'three';
import { useEffect, useState } from 'react';
import { antennaInfo } from '../importExport/data';
type typeFormData = {
  antennaModel: pickedModelData;
  theta: number;
  phi: number;
  thetaNumber: number;
  phiNumber: number;
};
let baseInfo = null;
const yAxis = [0, 1, 0];
const zAxis = [0, 0, 1];
const localAxesGroup = new Group();
const localAxesHelper = new AxesHelper(100);
localAxesGroup.add(localAxesHelper);

function CommandAntenna({ title, onClose }: FeaturedCmdDialogParams) {
  const [formData, setFormData] = useState<typeFormData>(null);
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      antennaModel: {
        type: 'string',
        format: PickInputRJSFFormat.PickModel,
      },
      theta: {
        type: 'number',
        title: 'theta',
        default: 0,
        minimum: -90,
        maximum: 90,
      },
      thetaNumber: {
        type: 'number',
        title: 'theta数值',
        default: 0,
        minimum: -90,
        maximum: 90,
      },
      phi: {
        type: 'number',
        title: 'phi',
        default: 0,
        minimum: 0,
        maximum: 360,
      },
      phiNumber: {
        type: 'number',
        title: 'phi数值',
        default: 0,
        minimum: 0,
        maximum: 360,
      },
    },
  };
  const uiSchema: UiSchema = {
    antennaModel: {
      'ui:placeholder': '请选择需要旋转的天线',
      'ui:autofocus': true,
    },
    theta: {
      'ui:widget': 'range',
    },
    phi: {
      'ui:widget': 'range',
    },
  };
  const handleSubmit = async () => {
    await executed(false);
    onClose();
  };
  const onPreview = async () => {
    previewer.clear();
    if (!isFormDataValid()) {
      return;
    }
    executed(true);
  };
  const setCurrentBox = async (id: string) => {
    if (!FeatureManager.isFeatureEnabled('set-current-box')) {
      return;
    }
    const parent = docMgr.documentObjects.filter(
      (item) =>
        item.type === 'GeomBox' &&
        item?.children?.length > 0 &&
        item?.children?.find((e) => e.dxid === id),
    );
    if (parent && parent.length > 0) {
      await wsApi.execCmd({
        c: 'SetCurrentBox',
        o: parent[0].dxid,
      });
      docMgr.workingObjectDxid = parent[0].dxid;
    }
  };
  const previewDelay = _.throttle(onPreview, 500, { leading: false });
  const executed = async (preview: boolean) => {
    const { antennaModel, theta, phi } = formData;
    if (theta == null || phi == null || !antennaModel) {
      return;
    }
    const origin = [baseInfo.x, baseInfo.y, baseInfo.z];
    const params = {
      mode: 'twoAxis',
      axis: [origin, yAxis],
      angle: theta,
      axis2: [origin, zAxis],
      angle2: phi,
      keepSrc: false,
      base: baseInfo.dxid,
    };
    await setCurrentBox(antennaModel.idInfo.o);
    const result = await wsApi.create3dRotate(
      antennaModel.idInfo.o,
      params,
      preview,
    );
    if (preview) {
      previewData(result);
    } else {
      await wsApi.setVisible(antennaModel.idInfo.o, false);
    }
  };
  const handleFormDataChange = async (newFormData) => {
    if (formData) {
      if (newFormData.theta != formData.theta) {
        setFormData({ ...newFormData, thetaNumber: newFormData.theta });
      } else if (newFormData.thetaNumber != formData.thetaNumber) {
        setFormData({ ...newFormData, theta: newFormData.thetaNumber });
      } else if (newFormData.phi != formData.phi) {
        setFormData({ ...newFormData, phiNumber: newFormData.phi });
      } else if (newFormData.phiNumber != formData.phiNumber) {
        setFormData({ ...newFormData, phi: newFormData.phiNumber });
      } else {
        setFormData(newFormData);
      }
    } else {
      setFormData(newFormData);
    }
    localAxesGroup.rotation.y = newFormData.theta * (Math.PI / 180);
    localAxesGroup.rotation.z = newFormData.phi * (Math.PI / 180);
  };
  const isFormDataValid = () => {
    if (
      formData?.antennaModel &&
      formData?.theta != null &&
      formData?.phi != null
    ) {
      return true;
    }
    return false;
  };
  useCommand('cmd-posture', {
    onClose,
  });
  useEffect(() => {
    if (!formData?.antennaModel) return;
    baseInfo = antennaInfo().getAntennaInfoById(
      formData?.antennaModel?.idInfo?.o,
    ).args;
    setFormData((state) => ({
      ...state,
      phi: baseInfo.phi,
      theta: baseInfo.theta,
      phiNumber: baseInfo.phi,
      thetaNumber: baseInfo.theta,
    }));

    localAxesGroup.position.set(0, 0, 0);
    localAxesGroup.position.set(baseInfo.x, baseInfo.y, baseInfo.z);
    localAxesGroup.rotation.order = 'ZYX';
    localAxesGroup.rotation.y = baseInfo.theta * (Math.PI / 180);
    localAxesGroup.rotation.z = baseInfo.phi * (Math.PI / 180);
    ctx2.cadScene.assisGroup.add(localAxesGroup);
  }, [formData?.antennaModel]);
  useEffect(() => {
    previewDelay();
  }, [formData]);
  return (
    <>
      <PickableCommandForm
        formData={formData}
        onPreview={onPreview}
        schema={schema}
        title={title}
        onChange={handleFormDataChange}
        onClose={onClose}
        onSubmit={handleSubmit}
        extraUiSchema={uiSchema}
        isFormDataValid={isFormDataValid()}
      />
    </>
  );
}

export const cmdAntenna: FeatureBaseCommand = {
  id: 'cmdAntenna',
  label: 'command.antenna-attitude',
  icon: 'commands/elec/elec-posture',
  create: (label, onClose, props) => (
    <CommandAntenna
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
